package com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.repository.HddcGminterpretationlineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.repository.HddcGminterpretationlineRepository;
import com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.repository.entity.HddcGminterpretationlineEntity;
import com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.service.HddcGminterpretationlineService;
import com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.viewobjects.HddcGminterpretationlineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGMInterpretationLine.viewobjects.HddcGminterpretationlineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-26
 */
@Service
public class HddcGminterpretationlineServiceImpl implements HddcGminterpretationlineService {

	@Autowired
    private HddcGminterpretationlineRepository hddcGminterpretationlineRepository;
    @Autowired
    private HddcGminterpretationlineNativeRepository hddcGminterpretationlineNativeRepository;

    @Override
    public JSONObject queryHddcGminterpretationlines(HddcGminterpretationlineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGminterpretationlineEntity> hddcGminterpretationlinePage = this.hddcGminterpretationlineNativeRepository.queryHddcGminterpretationlines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGminterpretationlinePage);
        return jsonObject;
    }


    @Override
    public HddcGminterpretationlineEntity getHddcGminterpretationline(String id) {
        HddcGminterpretationlineEntity hddcGminterpretationline = this.hddcGminterpretationlineRepository.findById(id).orElse(null);
         return hddcGminterpretationline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGminterpretationlineEntity saveHddcGminterpretationline(HddcGminterpretationlineEntity hddcGminterpretationline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGminterpretationline.setUuid(uuid);
        hddcGminterpretationline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGminterpretationline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGminterpretationline.setIsValid("1");
        hddcGminterpretationline.setQualityinspectionStatus("0");
        hddcGminterpretationline.setExtends10("1");
        this.hddcGminterpretationlineRepository.save(hddcGminterpretationline);
        return hddcGminterpretationline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGminterpretationlineEntity> saveHddcGminterpretationlineList(List<HddcGminterpretationlineEntity> list) {
        for (HddcGminterpretationlineEntity hddcGminterpretationline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGminterpretationline.setUuid(uuid);
            hddcGminterpretationline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGminterpretationline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGminterpretationline.setIsValid("1");
            hddcGminterpretationline.setQualityinspectionStatus("0");
            hddcGminterpretationline.setExtends10("1");
        }

        return hddcGminterpretationlineNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGminterpretationlineEntity updateHddcGminterpretationline(HddcGminterpretationlineEntity hddcGminterpretationline) {
        HddcGminterpretationlineEntity entity = hddcGminterpretationlineRepository.findById(hddcGminterpretationline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGminterpretationline);
        hddcGminterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGminterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGminterpretationlineRepository.save(hddcGminterpretationline);
        return hddcGminterpretationline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGminterpretationlines(List<String> ids) {
        List<HddcGminterpretationlineEntity> hddcGminterpretationlineList = this.hddcGminterpretationlineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGminterpretationlineList) && hddcGminterpretationlineList.size() > 0) {
            for(HddcGminterpretationlineEntity hddcGminterpretationline : hddcGminterpretationlineList) {
                hddcGminterpretationline.setIsValid("0");
                hddcGminterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGminterpretationline.setUpdateTime(new Date());
                this.hddcGminterpretationlineRepository.save(hddcGminterpretationline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGminterpretationlineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGminterpretationlineEntity> yhDisasterEntities = hddcGminterpretationlineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGminterpretationlineVO> list=new ArrayList<>();
        for (HddcGminterpretationlineEntity entity:yhDisasterEntities) {
            HddcGminterpretationlineVO yhDisasterVO=new HddcGminterpretationlineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"重磁解译线-线","重磁解译线-线",HddcGminterpretationlineVO.class,"重磁解译线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGminterpretationlineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGminterpretationlineVO.class, params);
            List<HddcGminterpretationlineVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGminterpretationlineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGminterpretationlineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcGminterpretationlineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGminterpretationlineEntity yhDisasterEntity = new HddcGminterpretationlineEntity();
            HddcGminterpretationlineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGminterpretationline(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGminterpretationlineEntity> hddcGminterpretationlineList = this.hddcGminterpretationlineRepository.queryHddcGminterpretationlinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGminterpretationlineList) && hddcGminterpretationlineList.size() > 0) {
            for(HddcGminterpretationlineEntity hddcGminterpretationline : hddcGminterpretationlineList) {
                hddcGminterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGminterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGminterpretationline.setIsValid("0");
                this.hddcGminterpretationlineRepository.save(hddcGminterpretationline);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGminterpretationlineEntity> hddcGminterpretationlineList = this.hddcGminterpretationlineRepository.queryHddcGminterpretationlinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGminterpretationlineList) && hddcGminterpretationlineList.size() > 0) {
            for(HddcGminterpretationlineEntity hddcGminterpretationline : hddcGminterpretationlineList) {
                hddcGminterpretationline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGminterpretationline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGminterpretationline.setIsValid("0");
                this.hddcGminterpretationlineRepository.save(hddcGminterpretationline);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("Code")){
            str+="Code,";
        }
        if(!set.contains("FaultName")){
            str+="FaultName,";
        }
        if(!set.contains("InterpretationAccordingG")){
            str+="InterpretationAccordingG,";
        }
        if(!set.contains("InterpretationAccordingM")){
            str+="InterpretationAccordingM,";
        }
        if(!set.contains("FaultDepth")){
            str+="FaultDepth,";
        }
        if(!set.contains("FaultAge")){
            str+="FaultAge,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveHddcGminterpretationlineFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcGminterpretationlineEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGminterpretationlineEntity data = new HddcGminterpretationlineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setCode(obs.get(2).toString());
                data.setFaultname(obs.get(3).toString());
                data.setInterpretationaccordingg(obs.get(4).toString());
                data.setInterpretationaccordingm(obs.get(5).toString());
                data.setFaultdepth(obs.get(6).toString());
                data.setFaultage(obs.get(7).toString());
                data.setCommentinfo(obs.get(8).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcGminterpretationlineList(datas);
        }
    }

    @Override
    public List<HddcGminterpretationlineEntity> findAll() {
        List<HddcGminterpretationlineEntity> list=this.hddcGminterpretationlineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGminterpretationlineRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGminterpretationlineEntity> hddcGminterpretationlineList = this.hddcGminterpretationlineRepository.queryHddcGminterpretationlineByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGminterpretationlineList) && hddcGminterpretationlineList.size() > 0) {
            hddcGminterpretationlineRepository.deleteAll(hddcGminterpretationlineList);
        }
    }

}
